#coding=utf-8
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
import django.contrib.auth as auth  
from django.contrib.auth.models import User

def login(request):
    previous = request.REQUEST.get('previous', '/')
    
    if request.method == "GET":
        return render_to_response('user/login.html', {'previous':previous})
    else:
        name = request.POST['username']
        password = request.POST['password']
        
        user = auth.authenticate(username=name, password=password)
        
        if user is not None:
            if user.is_active:
                auth.login(request, user)
                #return HttpResponse("%s:login success!"%user.username)
                return HttpResponseRedirect(previous)
            else:
                return render_to_response('user/login.html', 
                        {"message": "inactive user", 'previous':previous})
        else:
            return render_to_response('user/login.html', 
                        {"message": "invalid user", 'previous':previous})
        
        
def logout(request):
    auth.logout(request)
    previous = request.GET.get('previous', '/')
    return HttpResponseRedirect(previous)
    
def register(request):
    if request.method == "GET":
        return render_to_response('user/register.html')
    else:
        username = request.POST['username']
        password = request.POST['password']
        password_conf = request.POST['password_conf']
        email = request.POST['email']
        
        if password != password_conf:
            return render_to_response('register.html', {'message':'password diff'})
        
        try:
            User.objects.get(username=username)  
            return render_to_response('register.html', {'message':'user exists'})
        except User.DoesNotExist:
            user = User.objects.create_user(username=username, email=email, password=password)
        
            return HttpResponseRedirect('/login/')

